package zmcc.bsp.fabric.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class JsonUtils {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    private static ObjectMapper mapper ;
    static {
        mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static String toJson(Object value) {
        String json = "";
        try {
            json = mapper.writeValueAsString(value);
        } catch (Exception e) {

        }
        return json;
    }

    /**
     * 将json 对象转为Map
     *
     * @param jsondata
     * @return
     */
    public static Map<String, String> json2Map(String jsondata) {

        Map<String, String> map = new HashMap();

        try {
            map = mapper.readValue(jsondata, HashMap.class);
        } catch (IOException e) {
            logger.error("error:{}", e);
        }
        return map;
    }

    /**
     * 将json对象转为指定对象类型
     *
     * @param jsondata
     * @param valueTypeRef
     * @return
     */
    public static <T> T json2Object(String jsondata, TypeReference valueTypeRef) {

        T o = null;
        try {
            o = mapper.readValue(jsondata, valueTypeRef);
        } catch (Exception e) {
        }
        return o;
    }

    /**
     * 将json对象转为指定对象类型
     *
     * @param jsondata
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T json2Object(String jsondata, Class<T> tClass) {

        T o = null;
        try {
            o = mapper.readValue(jsondata, tClass);
        } catch (IOException e) {
            logger.error("error:{}", e);
        }
        return o;
    }

    /**
     * Json  获取List泛型数据
     *
     * @param clazz
     * @param json
     * @return
     */
    public static List jsoncastListType(Class clazz, String json) {
        List<Object> list = new ArrayList<Object>();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
        try {
            list = mapper.readValue(json, javaType);
        } catch (Exception e) {
            logger.error("error:{}", e);
        }
        return list;
    }


}
